package fileUtil

import (
	"os"
	"strings"
	"path/filepath"
	"errors"
	"io"
	"github.com/axgle/mahonia"
)

/**
文件是否存在
 */
func PathExists(path string) (bool) {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	return os.IsExist(err)
}

/**
转换编码格式
 */
func ConvertToString(src string, srcCode string, tagCode string) string {
	srcCoder := mahonia.NewDecoder(srcCode)
	srcResult := srcCoder.ConvertString(src)
	tagCoder := mahonia.NewDecoder(tagCode)
	_, cdata, _ := tagCoder.Translate([]byte(srcResult), true)
	result := string(cdata)
	return result
}

func CopyDir(form string, to string) error {
	form = strings.Replace(strings.Replace(form, "\\", "/", -1), "//", "/", -1)
	to = strings.Replace(strings.Replace(to, "\\", "/", -1), "//", "/", -1)
	if !PathExists(form) {
		return errors.New("起始文件不存在")
	}
	fileInfo, err := os.Stat(form)
	if err != nil {
		return err
	}
	name := fileInfo.Name()
	if PathExists(to + name) {
		err := os.RemoveAll(to + name)
		if err != nil {
			return err
		}
	}
	formSuffix := strings.TrimSuffix(form, name+"/")

	err = filepath.Walk(form, func(path string, f os.FileInfo, err error) error {
		if f == nil {
			return err
		}
		replace := strings.Replace(strings.Replace(path, "\\", "/", -1), "//", "/", -1)
		s := strings.Replace(replace, formSuffix, "", 1)
		if f.IsDir() {
			if formSuffix != path {
				os.MkdirAll(to+s, os.ModePerm)
			}
		} else {
			_, err := CopyFile(path, to+s)
			if err != nil {
				return err
			}
		}
		return nil
	})
	return err
}

//复制文件
func CopyFile(form, to string) (int64, error) {
	srcFile, err := os.Open(form)
	if err != nil {
		return 0, err
	}
	defer srcFile.Close()
	fileInfo, _ := os.Stat(form)
	name := fileInfo.Name()
	suffix := strings.TrimSuffix(to, name)
	if !PathExists(suffix) {
		err := os.MkdirAll(suffix, os.ModePerm)
		if err != nil {
			return 0, nil
		}
	}
	dstFile, err := os.Create(to)
	if err != nil {
		return 0, nil
	}
	defer dstFile.Close()
	return io.Copy(dstFile, srcFile)

}
